/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package wechat

import (
	"bytes"
	"encoding/json"
	"net/http"
	"errors"
)

// 发送消息到微信客户端
func SendMessage(msg *Message, originID string) error {
	if token, ok := GetAccessToken(originID); ok {
		u := "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token.Value
		buf := bytes.NewBuffer(nil)
		err := json.NewEncoder(buf).Encode(msg)
		if err != nil {
			return err
		}
		res, err := http.Post(u, "application/json;charset=UTF-8", buf)
		if err != nil {
			return err
		}
		var wErr = &weChatError{}
		decoder := json.NewDecoder(res.Body)
		err = decoder.Decode(&wErr)
		if err != nil {
			return err
		}
		res.Body.Close()
		if wErr.ErrCode != 0 {
			return wErr
		} else {
			return nil
		}
	} else {
		return errors.New("发送消息未成功，未获取 access_token")
	}
	return nil
}

type Message struct {
	ToUser  string  `json:"touser"`
	MsgType string  `json:"msgtype"`
	Text    *Text   `json:"text"`
	Image   *Media  `json:"image"`
	Voice   *Media  `json:"voice"`
	Video   *Media  `json:"video"`
	Music   *Music  `json:"music"`
	News    *News   `json:"news"`
	MpNews  *Media  `json:"mpnews"`
	WxCard  *WxCard `json:"wxcard"`
}

type WxCard struct {
	ID string `json:"card_id"`
}

type Music struct {
	Title        string `json:"title"`
	Description  string `json:"description"`
	Musicurl     string `json:"musicurl"`
	Hqmusicurl   string `json:"hqmusicurl"`
	ThumbMediaID string `json:"thumb_media_id"`
}

type Text struct {
	Content string `json:"content"`
}

type Media struct {
	ID           string `json:"media_id"`
	ThumbMediaID string `json:"thumb_media_id"`
	Title        string `json:"title"`
	Description  string `json:"description"`
}

type News struct {
	Articles []Article `json:"articles"`
}

type Article struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Url         string `json:"url"`
	Picurl      string `json:"picurl"`
}
